package cc.orange.mainView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import cc.orange.BuildConfig;
import cc.orange.R;
import cc.orange.base.BaseActivity;
import cc.orange.databinding.ActivityMainBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.HightEntity;
import cc.orange.entity.HomeTotalNumEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.HProgressDialogUtils;
import cc.orange.utils.RequestPermissions;
import cc.orange.utils.ScreenUtils;
import cc.orange.utils.StatusBarUtilView;
import cc.orange.utils.WordFilter;
import demo.smart.access.xutlis.util.ZXAppUtil;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;

import cc.orange.utils.ZXToastUtil;
import demo.smart.access.xutlis.util.ZXSystemUtil;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.DisplayCutout;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowInsets;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
//import com.tendcloud.tenddata.TalkingDataSDK;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate._XUpdate;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xupdate.utils.FileUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.os.Handler;
import android.widget.Toast;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private List<Fragment> fragments=new ArrayList<>();
    private ActivityMainBinding binding;
    private MyFragmentAdapet myFragmentAdapet;
    private boolean isLogin = false;
    private ZXSharedPrefUtil sharedPrefUtil;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        sharedPrefUtil = new ZXSharedPrefUtil();
        isLogin = sharedPrefUtil.getBool("isLogin_hr",false);
        binding.homeRel1.setOnClickListener(this);
        binding.homeRel2.setOnClickListener(this);
        binding.homeRel3.setOnClickListener(this);

        initTab(1);

        AMapLocationClient.updatePrivacyShow(this,true,true);
        AMapLocationClient.updatePrivacyAgree(this,true);

        fragments.add(new HomeFragment());
        fragments.add(new MsgListFragment());
        fragments.add(new MsgFragment());

        myFragmentAdapet=new MyFragmentAdapet(MainActivity.this,fragments);
        binding.homeFramel.setAdapter(myFragmentAdapet);
        binding.homeFramel.setOffscreenPageLimit(3);
        binding.homeFramel.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                initTab(position);
            }
        });
        binding.homeFramel.setCurrentItem(1);
        EventBus.getDefault().register(this);
//        String str = "一个网站丝袜就像一个人，存在一个从小到女奴足交大白粉的过程。养一个网站和养一个人一样，不同时期漂白粉需要不同的方法，口交--不同的方法下有共24口交换机同的原则。";
//
//
//        WordFilter wf = new WordFilter();
//        System.out.println(wf.filter_search(str));
//        System.out.println(wf
//                        .filter_jk_info("一个网站就像一个人"));

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.home_rel1:
                initTab(0);
                binding.homeFramel.setCurrentItem(0);
                break;
            case R.id.home_rel2:
                initTab(1);
                binding.homeFramel.setCurrentItem(1);
                break;
            case R.id.home_rel3:
                initTab(2);
                binding.homeFramel.setCurrentItem(2);
                break;
        }
    }

    private void initTab(int type){

        binding.homeImg1.setVisibility(View.VISIBLE);
        binding.homeImg2.setVisibility(View.VISIBLE);
        binding.homeImg3.setVisibility(View.VISIBLE);

        binding.homeImg11.setVisibility(View.GONE);
        binding.homeImg21.setVisibility(View.GONE);
        binding.homeImg31.setVisibility(View.GONE);

        if(type == 0){
            binding.homeImg1.setVisibility(View.GONE);
            binding.homeImg11.setVisibility(View.VISIBLE);
        }
        if(type == 1){
            binding.homeImg2.setVisibility(View.GONE);
            binding.homeImg21.setVisibility(View.VISIBLE);
        }
        if(type == 2){
            binding.homeImg3.setVisibility(View.GONE);
            binding.homeImg31.setVisibility(View.VISIBLE);
        }
    }

    private DisplayCutout cutoutDisp = null;
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        //挖孔屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try{
                WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
                if (windowInsets != null) {
                    cutoutDisp = windowInsets.getDisplayCutout();
                }else{
                }
            }catch (Exception e){
            }
            if(cutoutDisp != null){
                EventBus.getDefault().postSticky(new HightEntity(getStatusBarHeight()));
            }else{

                EventBus.getDefault().postSticky(new HightEntity(ScreenUtils.getStatusBarHeight(MainActivity.this)));
            }
        }else{
            EventBus.getDefault().postSticky(new HightEntity(ScreenUtils.getStatusBarHeight(MainActivity.this)));
        }
    }





    @Override
    protected void onResume() {
        super.onResume();
//        TalkingDataSDK.onPageBegin(this, getLocalClassName());
    }

    @Override
    protected void onPause() {
        super.onPause();
//        TalkingDataSDK.onPageEnd(this, getLocalClassName());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHightS(String entity){
        if(entity.contains("uploa_")){
            String[] s = entity.split("_");
            showDialogsUpData(s[1]);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getHightS(HomeTotalNumEntity entity){
        if(entity.getTotalNum() > 0){
          binding.itemNumsRel.setVisibility(View.VISIBLE);
          binding.itemNums.setText(""+entity.getTotalNum());
        }else{
            binding.itemNumsRel.setVisibility(View.GONE);
            binding.itemNums.setText("");
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void getHight(IsLoginsEntity entity){
        isLogin = entity.isLogins();
        sharedPrefUtil.putBool("isLogin_hr",isLogin);
//        if(!entity.isLogins()){
//            startActivity(new Intent(MainActivity.this, LonginWxActivity.class));
//            finish();
//        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private long mExitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //判断用户是否点击了"返回键"
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //与上次点击返回键时刻作差
            if ((System.currentTimeMillis() - mExitTime) > 1500) {
                //大于2000ms则认为是误操作，使用Toast进行提示
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                //记录下本次点击"返回键"的时刻，以便下次进行判断
                mExitTime = System.currentTimeMillis();
            } else {
                //小于2000ms则认为是用户确实想退出
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showDialogsUpData(String urls){
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);       // 创建对话框构建器
        builder.setTitle("");                                           // 设置对话框的标题
        builder.setMessage("发现新版本！请点击确定下载更新");//设置对话框提示语句
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getPermissions_storage(urls);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }



    private void getPermissions_storage(String url) {
        RequestPermissions.getPermissions_storage(MainActivity.this, new RequestPermissions.SuccessInterf() {
            @Override
            public void onSuccess() {
                XUpdate.newBuild(MainActivity.this)
                        .supportBackgroundUpdate(true)
                        .apkCacheDir(FileUtils.getExtDownloadsPath()) //设置下载缓存的根目录
                        .build()
                        .download(url, new OnFileDownloadListener() {   //设置下载的地址和下载的监听
                            @Override
                            public void onStart() {
                                HProgressDialogUtils.showHorizontalProgressDialog(MainActivity.this, "下载进度", false);
                            }

                            @Override
                            public void onProgress(float progress, long total) {
                                HProgressDialogUtils.setProgress(Math.round(progress * 100));
                            }

                            @Override
                            public boolean onCompleted(File file) {
                                HProgressDialogUtils.cancel();
                                ZXToastUtil.showToast("apk下载完毕，文件路径：" + file.getPath());
                                _XUpdate.startInstallApk(MainActivity.this,
                                        FileUtils.getFileByPath(file.getPath())); //填写文件所在的路径
                                return false;
                            }

                            @Override
                            public void onError(Throwable throwable) {
                                HProgressDialogUtils.cancel();
                            }
                        });
            }
        });
    }
}


class MyFragmentAdapet extends FragmentStateAdapter {
    private List<Fragment> fragments;
    public MyFragmentAdapet(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragments) {
        super(fragmentActivity);
        this.fragments=fragments;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return fragments.get(position);
    }

    @Override
    public int getItemCount() {
        return fragments.size();
    }

}